package mycoffee.order.task;

import java.util.concurrent.atomic.AtomicBoolean;

import mycoffee.order.utils.LogUtils;
import android.content.Context;
import android.os.AsyncTask;

/**
 * 
 * @author Tuong
 * 
 * @param <TParam>
 * @param <TProgress>
 * @param <TResult>
 */
public abstract class AbstractTask<TParam, TProgress, TResult> extends
		AsyncTask<TParam, TProgress, TResult> {

	/** use to notify the result to UI. */
	protected IDataEventHandler<TResult> mDataEventHandler;
	/** the flag used to cancel processing of thread. */
	protected final AtomicBoolean mShouldCancel = new AtomicBoolean(false);
	protected Context mContext;

	private final String TAG = "AbstractTask";

	public AbstractTask(Context context,
			IDataEventHandler<TResult> dataEventHandler) {
		mDataEventHandler = dataEventHandler;
		mContext = context;
	}

	public boolean getShouldCancel() {
		return mShouldCancel.get();
	}

	public void setShouldCancel(boolean shouldCancel) {
		this.mShouldCancel.set(shouldCancel);
	}

	@Override
	protected TResult doInBackground(TParam... params) {
		LogUtils.logDebug(TAG, "[doInBackground]- get data start");
		TResult result = doExecute();
		LogUtils.logDebug(TAG, "[doInBackground]- get data finish");
		return result;
	}

	@Override
	protected void onPostExecute(TResult result) {
		if (mDataEventHandler != null && !getShouldCancel()) {
			// notify to UI.
			mDataEventHandler.onNotify(result);
		}
	}

	/**
	 * execute query data from database.
	 * 
	 * @return list of data.
	 */
	protected abstract TResult doExecute();
}